package com.lits.file.controller;

import java.io.FileInputStream;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import com.lits.file.common.Resp;
import org.apache.commons.lang3.StringUtils;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.lits.file.common.UploadUtil;
import com.lits.file.config.LocalFileUploadCfg;
import com.lits.file.service.FileSvc;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

@Api(value = "文件接口")
@RestController
@RequestMapping("/api/file")
public class FileController {
	private static final Logger log = LoggerFactory.getLogger(FileController.class.getName());
	@Resource
	private LocalFileUploadCfg localFileUploadCfg;

	@Autowired
	private FileSvc fileSvc;

	@ApiOperation(value = "文件上传", notes = "上传有个根目录，然后拼接参数:文件存储位置，加上文件名称生成最终位置")
	@RequestMapping(value = "", method = RequestMethod.POST)
	public Resp<String[]> fileUpload(@ApiParam(value = "文件列表") @RequestParam("files") MultipartFile[] files,

                                     @ApiParam(value = "文件存储位置") @RequestParam("path") String path,

                                     @ApiParam(value = "是否按文件hash生成保存的文件名") @RequestParam(name = "hash", required = false, defaultValue = "true") boolean hash,

                                     @ApiParam(value = "是否覆盖") @RequestParam(name = "overwrite", required = false, defaultValue = "true") boolean overwrite,

                                     @RequestHeader(value = "Content-Type", defaultValue = "multipart/form-data", required = false) String contentType) {

		String destDir = null;
		if (UploadUtil.checkWrongPath(path)) {
            return new Resp<>("路径错误");
		} else {
			destDir = UploadUtil.joinFilePath(localFileUploadCfg.getBaseDir(), path);
		}
		String[] uploadedFileList;
		try {
			uploadedFileList = fileSvc.upload(files, destDir, hash, overwrite);
			return new Resp<>(uploadedFileList);
		} catch (NoSuchAlgorithmException | IOException e) {
			return new Resp<>("读写失败");
		}
	}

	@ApiOperation(value = "文件下载", notes = "文件path指的是上传时指定的path+文件名")
	@RequestMapping(value = "", method = RequestMethod.GET)
	public void fileDownload(@RequestParam("path") String path, HttpServletResponse response) throws IOException {
		String destDir = null;
		if (UploadUtil.checkWrongPath(path)) {
			log.error("路径错误:{}", path);
			response.setHeader("status", "404");
			return;
		} else {
			destDir = UploadUtil.joinFilePath(localFileUploadCfg.getBaseDir()) + StringUtils.strip(path, "\\/");
			FileInputStream inputStream = null;
			ServletOutputStream outputStream = response.getOutputStream();
			response.setHeader("Content-Disposition", "attachment;filename="
					+ new String(UploadUtil.getFileName(destDir).getBytes("UTF-8"), "ISO-8859-1"));
			try {
				inputStream = new FileInputStream(destDir);
				IOUtils.copy(inputStream, outputStream);
				outputStream.flush();
			} catch (Exception e) {
				log.error("file download failed, {}", destDir, e);
			} finally {
				UploadUtil.closeStream(inputStream);
			}
		}
	}

	@ApiOperation(value = "文件删除", notes = "文件path指的是上传时指定的path")
	@RequestMapping(value = "/{path}", method = RequestMethod.DELETE)
	public Resp<String[]> fileDelete(@PathVariable("path") String path, @RequestBody List<String> names)
			throws IOException {
		String destDir = null;
		if (UploadUtil.checkWrongPath(path)) {
			return new Resp<String[]>("路径错误：" + path);
		} else {

			if (CollectionUtils.isEmpty(names)) {
				return new Resp<>("请求的删除文件列表为空");
			} else {
				destDir = UploadUtil.joinFilePath(localFileUploadCfg.getBaseDir(), path);
				String[] deleted = new String[names.size()];
				int count = 0;
				// 循环删除请求的文件列表
				for (int i = 0; i < names.size(); i++) {
					String file = destDir + names.get(i);
					if (fileSvc.deleteFile(file)) {
						deleted[i] = names.get(i);
						count++;
					}
				}
				if (count == names.size()) {
					return new Resp<>(deleted);
				} else {
					return new Resp<>(false, "部分删除成功", deleted);
				}
			}
		}
	}

}
